<template>
  <div>
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 操作按钮区域 -->
    <div class="operation-serviceRegion">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增
      </el-button>
    </div>
    <!-- 数据表格 -->
    <el-card>
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="remark" label="角色描述" width="120"></el-table-column>
        <el-table-column prop="rolePermissions" label="角色权限" width="220">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.rolePermissions" :key="index">
              {{ getLabelPath(data, item) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                @click="updateStatus(scope.row)"
            >编辑
            </el-button>
            <el-button
                size="mini"
                type="primary"
                @click="bingUser(scope.row)"
            >授权用户
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row.id)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          class="pagination"
      ></el-pagination>
    </el-card>
    <el-dialog
        :visible.sync="bingUserDialogVisible"
        width="50%"
        @close="resetForm"
    >
      <UserSearch v-if="bingUserDialogVisible" @close="bingUserDialogVisible=false"/>
    </el-dialog>
    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="50%"
        @close="resetForm"
    >
      <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="120px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input v-model="formData.remark"></el-input>
        </el-form-item>
        <el-form-item label="角色权限" prop="longitude">
          <el-tree :data="data" ref="tree" node-key="id"
                   :default-checked-keys=checkedKeys
                   :show-checkbox="true" :props="defaultProps"></el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import {getInfo, add, update, updateStatus, delRole} from '@/api/role'
import {listPermission} from '@/api/permission'
import moment from 'moment';
import UserSearch from './components/UserSearch.vue'

export default {
  components: {UserSearch},
  data() {
    return {
      data: [],
      checkedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'label',
        value: 'id'
      },
      searchForm: {
        roleName: '',
        timeRange: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      tableData: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      bingUserDialogVisible: false,
      dialogTitle: '新增角色',
      formData: {
        roleName: '',
        remark: '',
        checkedIds: []
      },
      rules: {
        roleName: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
        remark: [{required: true, message: '请输入角色描述', trigger: 'blur'}],
      }
    }
  },
  mounted() {
    listPermission().then(res => {
      // login(this.formData).then(res => {
      console.log(res)
      this.loading = false
      if (res.code === 200) {
        // this.pagination.total = res.data.total
        // this.tableData = res.data.recordList

        this.data = res.data
      }
      // 处理登录成功逻辑
    }).catch(err => {
      this.loading = false
      console.log(err)
      // 错误已在拦截器统一处理
    })
  },
  created() {
    this.fetchData()
  },
  methods: {
    getLabelPath(tree, targetValue) {
      for (const node of tree) {
        if (node.id === targetValue) return node.label;
        if (node.children) {
          const childPath = this.getLabelPath(node.children, targetValue);
          if (childPath) return `${node.label}/${childPath}`;
        }
      }
      return '';
    },
    getSelected() {
      const leafNodes = this.$refs.tree.getCheckedNodes(true)
      // 获取选中节点的 key
      this.formData.checkedIds = leafNodes.map(node => node.id);

    },
    handleTimeChange(val) {
      this.searchForm.timeRange = val
      console.log('选择的时间范围:', val)
      // 这里可以触发查询或其他操作
    },
    formatTime(date) {
      console.log(date)
      return moment(date).format('YYYY-MM-DD HH:mm:ss');
    },
    fetchData() {
      this.loading = true
      getInfo(this.pagination.currentPage, this.pagination.pageSize, this.searchForm).then(res => {
        // login(this.formData).then(res => {
        console.log(res)
        this.loading = false
        if (res.code === 200) {
          this.pagination.total = res.data.total
          this.tableData = res.data.recordList
        }
        // 处理登录成功逻辑
      }).catch(err => {
        this.loading = false
        console.log(err)
        // 错误已在拦截器统一处理
      })
    },
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        phone: '',
        timeRange: []
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    handleAdd() {
      this.dialogTitle = '新增角色'
      this.dialogVisible = true


    },
    handleEdit(row) {
      this.dialogTitle = '编辑角色'
      this.formData = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    handleDelete(id) {
      this.$confirm('确认删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole(id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })

      }).catch(() => {
      })
    },
    bingUser(row) {
      this.bingUserDialogVisible = true
      console.log(row)
    },
    updateStatus(row) {
      updateStatus({id: row.id}).then(res => {
        if (res.code === 200) {
          console.log(res)
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.fetchData()
        }
      })
    },
    submitForm() {
      this.getSelected()
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let id = this.formData.id
          if (id !== undefined && id !== '') {
            update(this.formData).then(res => {
              if (res.code === 200) {
                console.log(res)
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.fetchData()
              }
            })
          } else {
            add(this.formData).then(res => {
              if (res.code === 200) {
                console.log(res)
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.fetchData()
              }

            })
          }


        }
      })
    },
    resetForm() {
      this.$refs.formRef.resetFields()
      this.formData = {
        roleName: '',
        remark: '',
        checkedIds: []
      }
    }
  }
}
</script>

<style scoped>
.service-phone-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-top: 10px;
}

.operation-phone {
  margin-bottom: 20px;
}

.operation-serviceRegion {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
